package controllers

import (
	"2301a-user2/cache"
	"2301a-user2/models"
	"context"
	beego "github.com/beego/beego/v2/server/web"
	"time"
)

var ctx = context.Background()

type UserController struct {
	beego.Controller
}

// msg
type Response struct {
	Code int         `json:"code"`
	Msg  string      `json:"msg"`
	Data interface{} `json:"data"`
}

// 注册
func (c *UserController) Register() {
	var err error

	//接收用户名和密码
	username := c.GetString("username")
	password := c.GetString("password")

	//验证用户名或密码不能为空
	if username == "" || password == "" {
		res := Response{
			Code: 500,
			Msg:  "用户名或密码不能为空",
			Data: nil,
		}
		c.Data["json"] = res
		c.ServeJSON()
		return
	}

	//接收user结构体
	var u models.User2
	u.Username = username
	u.Password = password
	err = u.Creat() //调用注册方法

	if err != nil {
		res := Response{
			Code: 500,
			Msg:  "注册失败",
			Data: nil,
		}
		c.Data["json"] = res
		c.ServeJSON()
		return
	}

	res := Response{
		Code: 200,
		Msg:  "注册成功",
		Data: nil,
	}
	c.Data["json"] = res
	c.ServeJSON()
	return
}

// 登录
func (c *UserController) Login() {
	var u models.User2
	//接收用户名和密码
	u.Username = c.GetString("username")
	u.Password = c.GetString("password")

	//验证用户名和密码不能为空
	if u.Username == "" || u.Password == "" {
		res := Response{
			Code: 500,
			Msg:  "用户名或密码不能为空",
			Data: nil,
		}
		c.Data["json"] = res
		c.ServeJSON()
		return
	}

	//用户名或密码错误，记录错误次数
	key := "login_fail_" + u.Username //错误次数键login_fail_zhang
	//记录失败错误
	count, _ := cache.Rdb.Get(ctx, key).Int()
	//判断失败错误 >=3
	if count >= 3 {
		res := Response{
			Code: 500,
			Msg:  "登录失败次数过多，请稍后再试",
			Data: nil,
		}
		c.Data["json"] = res
		c.ServeJSON()
		return
	}

	if u.CheckLogin() != nil {
		//记录错误次数 自增Incr
		cache.Rdb.Incr(ctx, key)
		//如果错误次数 >=3，自动锁定2分钟
		if count == 2 {
			cache.Rdb.Expire(ctx, key, time.Hour*2)
		}

		res := Response{
			Code: 500,
			Msg:  "用户名或密码错误",
			Data: nil,
		}
		c.Data["json"] = res
		c.ServeJSON()
		return
	}

	res := Response{
		Code: 200,
		Msg:  "登录成功",
		Data: nil,
	}
	c.Data["json"] = res
	c.ServeJSON()
	return

}
